package com.beimi.game;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.beimi.game.action.DelayAiAction;
import com.beimi.game.action.DelayNextTurn;
import com.beimi.game.common.TingPaiInfo;
import com.beimi.game.module.GameCardModule;
import com.beimi.game.module.GamePlayerModule;
import com.beimi.game.module.GameTurnModule;
import com.beimi.game.module.GameUserCmdModule;
import com.beimi.game.player.GamePlayer;
import com.beimi.game.player.PlayerCardModule;

public class MJService {

	protected static final Logger LOG = LoggerFactory.getLogger(MJService.class);

	private MajiongGame game;

	public MajiongGame getGame() {
		return game;
	}

	public void setGame(MajiongGame game) {
		this.game = game;
	}

	public void chuPai(GamePlayer player, int pai) {
		GameTurnModule turnModule = game.getModule(GameTurnModule.class);
		PlayerCardModule cardModule = player.getCardModule();

		if (turnModule.getCurrentTurn() != player.getSeat()) {
			LOG.warn("not your turn. {} {} {}", player.getName(), player.getSeat(), turnModule.getCurrentTurn());
			return;
		}

		if (!player.isCanChuPai()) {
			LOG.warn("no need chupai. {}", player.getName());
			return;
		}

		// //从此人牌中扣除
		boolean remove = cardModule.remove(pai);
		if (!remove) {
			return;
		}

		player.setCanChuPai(false);
		cardModule.checkCanTingPai();
		// userMgr.broacastInRoom('game_chupai_notify_push',{userId:seatData.userId,pai:pai},seatData.userId,true);
		//
		// //如果出的牌可以胡，则算过胡
		Map<Integer, TingPaiInfo> tingMap = player.getCardModule().getTingMap();
		if (tingMap.containsKey(pai)) {
			cardModule.setGuoHuFan(tingMap.get(pai).getFan());
		}
		//
		// //检查是否有人要胡，要碰 要杠
		boolean hasActions = false;
		GamePlayer[] players = game.getModule(GamePlayerModule.class).getPlayers();
		for (int i = 0; i < players.length; ++i) {
			// //玩家自己不检查
			if (turnModule.getCurrentTurn() == player.getSeat()) {
				continue;
			}

			PlayerCardModule other = players[i].getCardModule();
			// 未胡牌的才检查杠和碰
			if (!other.isHued()) {
				other.checCanPeng(pai);
				other.checkCanDianGang(pai);
			}

			other.checkCanHu(pai);
			if (other.getLastFangGangSeat() == -1) {

				if (other.isCanHu() && other.getGuoHuFan() >= 0
						&& other.getTingMap().get(pai).getFan() <= other.getGuoHuFan()) {
					// console.log("ddd.guoHuFan:" + ddd.guoHuFan);
					other.setCanHu(true);
					// userMgr.sendMsg(ddd.userId,'guohu_push');
				}
			}
			//
			if (cardModule.hasOperation() && players[i].getClient() != null) {
				players[i].sendMessage("game_operate_push", JSON.toJSONString(cardModule));
				// sendOperations(game, ddd, game.chuPai);
				hasActions = true;
			}
		}

		// 如果没有人有操作，则向下一家发牌，并通知他出牌
		if (!hasActions) {
			delayNextTurn(5000);
		}
	}

	private void delayNextTurn(int delay) {
		game.getModule(GameUserCmdModule.class).add(new DelayNextTurn(this, 5000));
	}

	public void randomChuPai(GamePlayer player) {
		int pai = player.getCardModule().getHolds().get(0);
		chuPai(player, pai);
	}

	public void doUserMoPai() {
		game.setChuPai(-1);
		
	
		GamePlayerModule playerModule = game.getModule(GamePlayerModule.class);
		GameTurnModule turnModule = game.getModule(GameTurnModule.class);
		GamePlayer player = playerModule.getPlayers()[turnModule.getCurrentTurn()];
		GameCardModule cardModule = game.getModule(GameCardModule.class);

		if (!cardModule.hasPai()) {
			game.setState(2);
			return;
		}
		
		player.getCardModule().beginMoPai();
		player.getCardModule().mopai(cardModule);
		player.setCanChuPai(true);

		if (player.getClient() == null) {
			randomChuPai(player);
		} else {
			waitingUserChuPai(player);
		}
	}

	private void waitingUserChuPai(GamePlayer player) {
		game.getModule(GameUserCmdModule.class).add(new DelayAiAction(player, this, 5000));
	}

	public void nextTurn() {
		int turn = game.getModule(GameTurnModule.class).incrTurn();
		game.getModule(GamePlayerModule.class).broacastInRoom("game_turn_push", turn, null);

		doUserMoPai();
		LOG.info("next turn {}", turn);
	}
}
